/*
 * @Author: hruomei
 * @Title: 关于登录/退出登录的公共文件
 * @Description: 为了方便维护,用户主动退出,强制退出逻辑,统一写到这个文件
 * @CreateTime: 2019/10/01
 * @LastUpDateTime: 2020/01/20
 * @Version: V1.03
*/

import {
	THIS as instance
} from './api.js'
import CryptoJS from '../plugins/aes.js'
import {
    outlogin,
    gettwotokenbyemmtoken
} from './service.js'

// 用户主动退出
export function initiativeLogout() {
	outlogin({
		token: instance.$api.getToken(),
		loading: false
	}).then(result => {
		if (result.success) {
			// #ifdef APP-PLUS
			plus.push.clear();
			// #endif

			uni.removeStorageSync(instance.$config.userInfoKey);

			let pages = getCurrentPages(),
				route = pages.length > 0 ? pages[pages.length - 1].route : void 0;

			// 如果当前已经在登录页,说明已经注销登录,不弹框
			if(route && route.indexOf('login/login') != -1) {
				return;
			}

			uni.reLaunch({
				// url: "/pages/framework/login/login?update=1"
                url: "/workspaces/views/login/login?update=1"
			});
		}
	});
}

// 由于token过期等被强制退出
export function forceLogout() {
	// #ifdef APP-PLUS
	plus.push.clear();
	// #endif

	uni.removeStorageSync(instance.$config.userInfoKey);
	uni.reLaunch({
		// url: `/pages/framework/login/login?update=1`
        url: "/workspaces/views/login/login?update=1"
	});
}

// 返回退出登录前的页面
export function redirectToBackPage(pageOptions) {
	let userInfo = instance.$api.getUserInfo(),
		requestFailMap = Object.assign(instance.$config.requestFailMap), // 被强制退出登录时,需要重新发起请求
		lastUser = uni.getStorageSync('FRAMEWORK_FORCE_LOGOUT_USER');

	// 清除tabbar页面的缓存,避免白屏,缓存上一个用户的数据等问题
	uni.$emit('FRAMEWORK_UPDATE_TABPAGE_INFO');
	instance.$config.requestFailMap = {};

	if (pageOptions.backpage && pageOptions.backtype && lastUser) {
		let pages = getCurrentPages(),
			page = pages[pages.length - 1],
			route = page.route;

		// 不能跳转回自身页面
		if (pageOptions.backpage.indexOf(route) === -1  && lastUser === userInfo.ly_id) {
			if (Number(pageOptions.backtype) === 1) {
				uni.navigateBack({
					delta: 1,
					fail() {
						uni.switchTab({
							url: '../index/index'
						});
					}
				});
			} else {
				uni.switchTab({
					url:pageOptions.backpage
				});
			}
		} else {
			uni.switchTab({
				url: '../index/index'
			});
		}

		uni.removeStorageSync('FRAMEWORK_FORCE_LOGOUT_USER');
	} else {
		uni.switchTab({
			url: '../index/index'
		});
	}
}

// 登录加密方法
export function encryptNoPadding(data) {
	let key = CryptoJS.enc.Utf8.parse('kent20180816mpjs');
	let iv = CryptoJS.enc.Utf8.parse('kent20180816mpjs');

	return CryptoJS.AES.encrypt(data, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	}).toString();
}

export function decryptNoPadding(data) {
	let key = CryptoJS.enc.Utf8.parse('kent20180816mpjs');
	let iv = CryptoJS.enc.Utf8.parse('kent20180816mpjs');

	return CryptoJS.AES.decrypt(data, key, {
		iv: iv,
		mode: CryptoJS.mode.CBC,
		padding: CryptoJS.pad.ZeroPadding
	}).toString();
}

export function getAccessToken(resolve) {
	try {
		let userInfo = instance.$api.getUserInfo();
		if (userInfo.accessToken && userInfo.refreshToken) {
			resolve({
				accessToken: userInfo.accessToken,
				refreshToken: userInfo.refreshToken
			});
		} else {
			gettwotokenbyemmtoken({
				loading: false
			}).then(result => {
				if (result && result.success) {
					resolve(result.data.rows);

					instance.$api.setUserInfo(Object.assign(userInfo, result.data.rows));
				} else {
					instance.$api.unSuccessHandleFn('获取token', result);
				}
			}).catch(e =>{
				instance.$api.errorHandleFn(e);
			});
		}
	} catch(e) {
		instance.$api.showModalWithCloseButton('程序异常');
		console.error(e);
	}
}

export function clearLastUserStorage() {
    const fileCache = uni.getStorageSync('FRAMEWORK_IMAGE_CACHE_INFO');

    uni.removeTabBarBadge({
        index: 1
    });
    uni.clearStorageSync();
    uni.setStorageSync('FRAMEWORK_IMAGE_CACHE_INFO', fileCache); // 为了尽可能的利用缓存文件
}

export function forceResetPwd() {
	instance.$api.navigateTo('/pages/framework/login/forceResetPwd', {
		access_token: '',
		username: instance.$api.getUserInfo().ly_loginname,
		type: '2'
	});
}

export default {
	initiativeLogout,
	forceLogout,
	redirectToBackPage,
	encryptNoPadding,
	decryptNoPadding,
	getAccessToken,
    clearLastUserStorage,
	forceResetPwd
}
